package gateway.config.security.util;

import cn.hutool.json.JSONUtil;
import gateway.model.dto.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Security工具类
 *
 * @author 米泽鹏
 * @since 2022-12-1 下午 6:13
 */
@Slf4j
public class SecurityUtil {

	private SecurityUtil() {
		throw new AssertionError("不可实例化");
	}

	/**
	 * 通过Security获取当前登录用户的用户名
	 *
	 * @return String 当前登录用户的用户名
	 */
	public static String getCurrentUsername() {
		Object object = getPrincipal();
		if (object == null) {
			return null;
		}
		if (object instanceof SecurityUser) {
			SecurityUser securityUser = ((SecurityUser) object);
			log.info("获取到当前操作人：" + securityUser.getUsername());
			return securityUser.getUsername();
		} else {
			log.info("获取到当前操作人：" + object);
			return object.toString();
		}
	}

	/**
	 * 通过Security获取当前登录用户的id
	 *
	 * @return Long 当前登录用户的id
	 */
	public static Long getCurrentUserId() {
		Object object = getPrincipal();
		if (object == null) {
			return null;
		}
		if (object instanceof SecurityUser) {
			SecurityUser securityUser = ((SecurityUser) object);
			log.info("获取到当前操作人：" + securityUser.getUsername());
			return securityUser.getUserId();
		} else {
			log.warn("未知的当前操作人：{}", JSONUtil.toJsonStr(object));
			return null;
		}
	}

	public static Object getPrincipal() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			log.warn("无法获取当前操作人，authentication为null");
			return null;
		}
		Object object = authentication.getPrincipal();
		if (object == null) {
			log.warn("无法获取当前操作人，authentication.getPrincipal()为null");
			return null;
		}
		return object;
	}

}
